﻿using System;
using System.Collections.Generic;
using BLWCMS.Core.IBusiness;
using BLWCMS.Core.Models;
using Simple.Data;

namespace BLWCMS.Core.Business
{
    public class WeixinConfigBusiness:IWeixinConfigBusiness
    {
        /// <summary>
        /// 写入配置项
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void WriteConfig(string name, string value)
        {
            if (!string.IsNullOrEmpty(name))
            {
               var db = Database.OpenConnection(Dbcontext.ConnectionString);
                db.BL_Configs.UpdateByName(Name: name, Value: value);
            } 
        }

        /// <summary>
        /// 读取配置项
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string ReadConfig(string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                var db = Database.OpenConnection(Dbcontext.ConnectionString);
                ConfigModel configModel = db.BL_Configs.FindByName(name);
                return configModel.Value;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 写入微信配置项
        /// </summary>
        /// <param name="weixinConfigModel"></param>
        /// <returns></returns>
        public string WriteWeixinConfig(WeixinConfigModel weixinConfigModel)
        {
            try
            {
                WriteConfig("WeixinType", Convert.ToString(weixinConfigModel.WeixinType));
                WriteConfig("WeixinToken", weixinConfigModel.WeixinToken);
                WriteConfig("WeixinEncodingAESKey", weixinConfigModel.WeixinEncodingAesKey);
                WriteConfig("WeixinAppId", weixinConfigModel.WeixinAppId);
                WriteConfig("WeixinAppSecret", weixinConfigModel.WeixinAppSecret);

                return ResCode.N200("保存成功！", "/binding");
            }
            catch (Exception e)
            {
                return ResCode.N500(e.Message);
            }
        }

        /// <summary>
        /// 读取微信配置项
        /// </summary>
        /// <returns></returns>
        public WeixinConfigModel GetModel()
        {
            WeixinConfigModel weixinConfigModel = new WeixinConfigModel
            {
                WeixinType = Convert.ToInt32(ReadConfig("WeixinType")),
                WeixinToken = ReadConfig("WeixinToken"),
                WeixinEncodingAesKey = ReadConfig("WeixinEncodingAesKey"),
                WeixinAppId = ReadConfig("WeixinAppId"),
                WeixinAppSecret = ReadConfig("WeixinAppSecret")
            };
            return weixinConfigModel;
        }
    }
}
